package com.light.mytext.http

import android.content.Context
import com.android.tu.loadingdialog.LoadingDailog
import com.blankj.utilcode.util.Utils.runOnUiThread
import com.google.gson.Gson
import com.light.mytext.views.CustomProgress
import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * okHttp
 */
class OKHttpRequestUtils {

    private var mWaitDialog: LoadingDailog? = null
    var Tag = "RequestUtils"
    var mcontext: Context? = null
    private var call: Call? = null
//    private var mWaitDialog: CustomProgress? = null
    constructor(context: Context, isLoading: Boolean) {
        this.mcontext = context
        if (context != null && isLoading) {
//            mWaitDialog = CustomProgress.setDialog(context, "加载中...", null)
//            mWaitDialog!!.setCancelable(false)
//            mWaitDialog!!.setOnCancelListener { call!!.cancel() }
            val loadBuilder = LoadingDailog.Builder(mcontext)
                .setMessage("加载中...")
                .setCancelable(false)
                .setCancelOutside(false)
            mWaitDialog = loadBuilder.create()
            showDialog()
        }
    }

    fun <T> add(
        url: String,
        map: HashMap<String, String>,
        mClass: Class<T>, isPost: String,
        callBack: HttpCallBack<T>
    ) {
        if ("POST" == isPost) {
            post(url, map, mClass, callBack)
        } else {
            get(url, map, mClass, callBack)
        }
    }
    /**
     * post请求
     */
    fun <T> post(
        url: String,
        map: HashMap<String, String>,
        mClass: Class<T>,
        callBack: HttpCallBack<T>
    ){




    }

    /**
     * get请求
     */
    fun <T> get(
        url: String,
        map: HashMap<String, String>,
        mClass: Class<T>,
        callBack: HttpCallBack<T>
    ) {
        // 1.拿到OkHttpClient对象
        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS) //设置连接超时时间
            .readTimeout(20, TimeUnit.SECONDS) //设置读取超时时间
            .build()
        //2 . 构造Request对象
        var request = Request.Builder()
            .get()
            .url(urlAppend(url, map))
            .build()
        //3 . 将Request封装为Call
        call = client.newCall(request)
        call!!.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                dismiss()
                runOnUiThread {//回到主线程
                    callBack?.onFailed("" + e.message)
                }
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body()!!.string() //修改后
                var gson = Gson()
                var data: T = gson.fromJson(result, mClass) ?: return
                dismiss()
                runOnUiThread {//回到主线程
                    callBack?.onResponse(true, response.message(), data)
                }

            }

        })

    }

    /**
     * 拼接Url
     */
    fun urlAppend(baseUrl: String, params: HashMap<String, String>): String {
        var stringBuffer = StringBuffer("")
        stringBuffer.append(baseUrl)
        var size = 0
        if (params != null && params.size != 0) {
            params.entries.forEach {
                if (size == 0) {
                    stringBuffer.append("?" + it.key + "=" + it.value)
                    size++
                } else {
                    stringBuffer.append("&" + it.key + "=" + it.value)
                }
            }
        }
        return stringBuffer.toString()
    }

    interface HttpCallBack<T> {
        fun onResponse(result: Boolean, message: String, data: Any?)
        fun onFailed(message: String)
    }

    fun showDialog() {
        if (mWaitDialog != null && !mWaitDialog!!.isShowing) {
            mWaitDialog!!.show()
        }
    }

    fun dismiss() {
        if (mWaitDialog!!.isShowing) {
            mWaitDialog!!.dismiss()
        }
    }


}